package com.ctsi.oppo.controller;

import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.oppo.entity.BusinessOppoEntity;
import com.ctsi.oppo.query.OppoQueryParam;
import com.ctsi.oppo.service.OppoService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@RestController
public class BusinessOppoController {
    private static final Logger logger= LoggerFactory.getLogger(BusinessOppoController.class);

@Autowired
private OppoService oppomapper;

    /**
     * 下载方法一
     * @param res
     * @param req
     * @param name
     * @throws Exception
     */

    @GetMapping(value = "/product/downloadExcel")
    public void downloadExcel(HttpServletResponse res, HttpServletRequest req,String name) throws Exception {
    String fileName = "商机数据模板.xlsx";
    ServletOutputStream out;
    res.setContentType("multipart/form-data");
    res.setCharacterEncoding("UTF-8");
    res.setContentType("text/html");
    String filePath = System.getProperty("java.io.tmpdir")+fileName;
    String userAgent = req.getHeader("User-Agent");
    if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
    } else {
    // 非IE浏览器的处理：
       fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
    }
    filePath = URLDecoder.decode(filePath, "UTF-8");
    res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
    FileInputStream inputStream = new FileInputStream(filePath);
    out = res.getOutputStream();
    int b = 0;
    byte[] buffer = new byte[1024];
    while ((b = inputStream.read(buffer)) != -1) {
    // 4.写到输出流(out)中
    out.write(buffer, 0, b);
    }
    inputStream.close();

    if (out != null) {
    out.flush();
    out.close();
    }
    }

    /**
     * 下载方法二
     * @param res
     */
    @RequestMapping(value = "/excel/download",method = RequestMethod.GET)
    public  void downexcel(HttpServletResponse res){
        try {
            //获取要下载的模板名称
            String fileName = "商机数据模板.xlsx";
            //设置要下载的文件的名称
            res.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            res.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径（系统临时路径）
//            String filePath = getClass().getResource("/template/" + fileName).getPath();
            String folder=System.getProperty("java.io.tmpdir")+fileName;
            //excel模板路径
//            String cfgFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/111.xlsx").getPath();
            FileInputStream input = new FileInputStream(new File(folder));
            //            FileInputStream input = new FileInputStream(new File("d://"+fileName));
            OutputStream out = res.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
            res.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
            System.out.println("商机模板下载完成");
        } catch (Exception ex) {
            System.out.println("商机导入模板下载失败！");
        }
    }


        /**
         * 导入excel
         */
        @RequestMapping(value = "/oppo/import",method = RequestMethod.POST)
        @ResponseBody
        public String excelImport(@RequestParam(value="filename") MultipartFile file, HttpSession session){
            int result = 0;
            try {
                result = this.addOppo(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(result > 0){
                return "excel文件数据导入成功！";
            }else{
                return "excel数据导入失败！";
            }
        }
    /**
     * 商机列表查询
     */
    @PostMapping(value = "/oppo/selectOppoList", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<BusinessOppoEntity>> queryQuestionListById(@RequestBody OppoQueryParam ppp) {
//        if (UtilValidate.isNotEmpty(ppp.getStartDate())) {
//            ppp.setStartDate(String.valueOf(UtilDateTime.toLong(ppp.getStartDate())));
//        }
//        if (UtilValidate.isNotEmpty(ppp.getEndDate())) {
//            ppp.setEndDate(String.valueOf(UtilDateTime.toLong(ppp.getEndDate())));
//        }
        Page<BusinessOppoEntity> result = oppomapper.selectMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)), ppp.getStart(), ppp.getPageSize());
//        List<QuestionLibVo> questionLibVos = result.getResult().stream().map(lib -> {
//            QuestionLibVo questionLibVo = voTemplate.defaultExcute(new QuestionLibVo(), lib);
//            questionLibVo.setCreateDateStr(UtilDateTime.longToString(lib.getCreate_date()));
//            return questionLibVo;
//        }).collect(Collectors.toList());
//        new Page<>(ppp.getStart(), result.getTotalCount(), result.getPageSize(), questionLibVos)
        return UnifiedResponse.ok(result);
    }

    /**
     * 删除
     */
    @PostMapping(value = "/oppo/deleteByPrimaryKey")
    public UnifiedResponse<String> deleteByPrimaryKey(@RequestParam(value = "ids") String ids){
        if (UtilValidate.isNotEmpty(ids)) {
            String[] arr = ids.split(",");
            int result = Stream.of(arr).filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    return this.oppomapper.deleteByPrimaryKey(id);
                }catch (Exception e){
                    logger.error("{}",e);
                    return 0;
                }
            }).sum();
            if(arr.length >1){
                return UnifiedResponse.ok("选中"+arr.length+"条数据，成功删除"+result+"条数据！");
            }else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }

    /**
     *excel导入
     */
public int addOppo(MultipartFile file) throws Exception {
    int result = 0;
//		存放excel表中所有Oppo细腻
    List<BusinessOppoEntity> userList = new ArrayList<>();
    /**
     *
     * 判断文件版本
     */
    String fileName = file.getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
    InputStream ins = file.getInputStream();
    Workbook wb = null;
    if(suffix.equals("xlsx")){
        wb = new XSSFWorkbook(ins);
    }else {
        wb=new HSSFWorkbook(ins);
    }
    /**
     * 获取excel表单
     */
    Sheet sheet = wb.getSheetAt(0);
    /**
     * line = 2 :从表的第三行开始获取记录
     *
     */
    if(null != sheet){
        for(int line = 2; line <= sheet.getLastRowNum();line++){
            BusinessOppoEntity user = new BusinessOppoEntity();
            Row row = sheet.getRow(line);
            if(null == row){
                continue;
            }
            /**
             * 判断单元格类型是否为文本类型
             */
//            if(1 != row.getCell(0).getCellType()){
//                throw new MyException("单元格类型不是文本类型！");
//            }
            /**
             * 获取第一个单元格的内容
             */
            row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);

            String hangye = row.getCell(0).getStringCellValue();

            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            /**
             * 获取第二个单元格的内容
             */
            String name = row.getCell(1).getStringCellValue();
            row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
            String status=row.getCell(2).getStringCellValue();
            user.setHangye(hangye);
            user.setSjname(name);
            user.setSjstatus(status);
            user.setId(UUIDGenerator.getId());
            userList.add(user);
        }

        for(BusinessOppoEntity userInfo:userList){

            /**
             * 判断数据库表中是否存在用户记录，若存在，则更新，不存在，则保存记录
             */
            String name = userInfo.getSjname();

            int count = oppomapper.selectOppoByName(name);

            if(0 == count){
                result = oppomapper.insertOppoNumber(userInfo);
            }else{
                result = oppomapper.updateOppoByPKSelective(userInfo);
            }
        }
    }

    return result;
}




}
